Skip to content

fix: return null for avg() of empty array#105

Open
spokodev wants to merge 1 commit into
jmespath:masterfrom
spokodev:fix-avg-empty-array
Open

fix: return null for avg() of empty array#105
spokodev wants to merge 1 commit into
jmespath:masterfrom
spokodev:fix-avg-empty-array

Conversation

@spokodev

Copy link
Copy Markdown

Bug

avg() over an empty array returns NaN instead of null:

jmespath.search({e: []}, 'avg(e)'); // => NaN, expected null

The cause is _functionAvg computing sum / inputArray.length, which is 0 / 0 = NaN when the array is empty.

Spec

The JMESPath specification for avg() states: "An empty array will produce a return value of null." (https://jmespath.org/specification.html#avg)

The official compliance suite already has the case avg(empty_list) -> null in functions.json. The copy vendored in this repo's test/compliance/functions.json predated that case, so the gap went unnoticed.

Fix

Guard the empty case at the top of _functionAvg:

_functionAvg: function(resolvedArgs) {
    var sum = 0;
    var inputArray = resolvedArgs[0];
    if (inputArray.length === 0) {
        return null;
    }
    for (var i = 0; i < inputArray.length; i++) {
        sum += inputArray[i];
    }
    return sum / inputArray.length;
},

Also adds the missing compliance case avg(empty_list) -> null to test/compliance/functions.json (the empty_list input already exists in the suite's given block).

The added test fails before the fix (NaN should loosely deep-equal null) and passes after. Full suite green: 889 passing.

avg() over an empty array returned NaN (0/0) instead of null. The JMESPath spec states an empty array produces a return value of null. Guard the empty case before the sum loop and add the compliance case avg(empty_list) = null.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant